package com.powernode.shop.gateway.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.powernode.shop.gateway.constant.GatewayConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.List;

/**
 * @author ZHAOZHENYU
 * @since 2022/10/10
 */

@Component
public class JWTCheckFilter implements GlobalFilter, Ordered {

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 解析oauth-server的token 并验证
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 请求路径
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        // oauth/token放行
        if (GatewayConstant.ALLOW_URLS.contains(path)) return chain.filter(exchange);
        List<String> authList = request.getHeaders().get(GatewayConstant.AUTHORIZATION);
        if (!CollectionUtils.isEmpty(authList)){
            String authorization = authList.get(0);
            if (StringUtils.hasText(authorization)){
                // 去除bearer
                String jwtToken = authorization.replaceAll(GatewayConstant.BEARER, "");
                // redis里面有对用权限信息缓存
                if (StringUtils.hasText(jwtToken) && redisTemplate.hasKey(GatewayConstant.OAUTH_JWT_PREFIX + jwtToken)) {
                    return chain.filter(exchange);
                }
            }
        }

        // 否则拦截
        ServerHttpResponse response = exchange.getResponse();
        response.getHeaders().add("content-type", "application/json;charset=utf-8");

        HashMap<String, Object> map = new HashMap<>(4);
        map.put("code", HttpStatus.UNAUTHORIZED.value());
        map.put("msg", "未授权");

        ObjectMapper objectMapper = new ObjectMapper();
        byte[] bytes = new byte[0];
        try {
            // 转化为json流
            bytes = objectMapper.writeValueAsBytes(map);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        // 以流的方式写入前端响应
        DataBuffer wrap = response.bufferFactory().wrap(bytes);
        return response.writeWith(Mono.just(wrap));
    }

    /**
     * 值越小越先被执行 这个filter类优先被spring加载
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
